package com.ostrich.module_player

import android.content.res.Configuration
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.gyf.immersionbar.ImmersionBar
import com.ostrich.library_base.BaseMvvmActivity
import com.ostrich.library_common.bean.VideoBean
import com.ostrich.library_common.route.RouterActivityPath
import com.ostrich.library_common.utils.LoggerUtils
import com.ostrich.library_video.views.CoverVideoPlayerView
import com.ostrich.module_player.adapter.PlayerAdapter
import com.ostrich.module_player.databinding.PlayerActivityPlayerBinding
import com.ostrich.module_player.databinding.PlayerItemVideoHeaderViewBinding
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.GSYVideoHelper
import com.shuyu.gsyvideoplayer.utils.OrientationUtils

@Route(path = RouterActivityPath.PAGER_PLAYER)
class PlayerActivity : BaseMvvmActivity<PlayerActivityPlayerBinding,PlayerViewModel>() {

    @Autowired
    lateinit var video:VideoBean
    var isPause = false //是否暂停
    var isPlay = true //是否播放
    lateinit var orientationUtils:OrientationUtils

    private lateinit var playerAdapter: PlayerAdapter
    override fun initView() {
        ARouter.getInstance().inject(this)       //注入
        //状态栏
        ImmersionBar.with(this)
            .statusBarView(binding?.topView)
            .init()
        //列表
        initRV()
        //背景红蓝图
        initBg()
        //视频播放
        initVideoView()

    }
    private fun initBg(){
        binding?.let {
            //显示背景大图
            it.blurred = video.blurredUrl
            it.executePendingBindings()
        }
    }
    private fun initRV(){
        binding?.let {
            playerAdapter = PlayerAdapter()
            it.rv.adapter = playerAdapter
            it.rv.layoutManager = LinearLayoutManager(this)
            it.rv.setHasFixedSize(true)
            //设置前要有layoutManager
            playerAdapter.addHeaderView(getHeaderView())//头布局
            playerAdapter.addFooterView(getFooterView())//尾布局
        }
    }
    private fun initVideoView(){
        binding?.let {
            //封面图片
            val imageView = ImageView(this)
            Glide.with(this).load(video.blurredUrl)
                .into(imageView)
            //屏幕旋转帮助类
            orientationUtils = OrientationUtils(this,it.cvVideoView)
            orientationUtils.isEnable = false

            //构建者模式
            val gsyVideoHelperBuilder = GSYVideoHelper.GSYVideoHelperBuilder()
            gsyVideoHelperBuilder
                .setVideoTitle(video.videoTitle)//设置标题
                .setUrl(video.playerUrl)//设置视频资源
                .setThumbImageView(imageView)//设置封面
                .setCacheWithPlay(true)//设置是否缓存
                .setShowFullAnimation(true)//设置全屏动画
                .setIsTouchWiget(true)//设置是否支持触摸
                .setNeedOrientationUtils(true)//是否设置OrientationUtils
                .setRotateViewAuto(false)
                .setLockLand(true)//全屏就锁屏横屏，默认false竖屏，可配合setRotateViewAuto使
                .setVideoAllCallBack(object :GSYSampleCallBack(){//回调
                    override fun onPrepared(url: String?, vararg objects: Any?) {
                        super.onPrepared(url, *objects)
                        // 开始播放了才能旋转和全屏
                        orientationUtils.isEnable = true
                    }

                    override fun onQuitFullscreen(url: String?, vararg objects: Any?) {
                        super.onQuitFullscreen(url, *objects)
                        //列表返回的样式判断。因为立即旋转会导致界面跳动的问题
                        if (orientationUtils != null) {
                            orientationUtils.backToProtVideo()
                        }
                    }

                })
                .build(it.cvVideoView)//和视频播放器绑定
            //点击返回键盘
           it.cvVideoView.backButton.setOnClickListener {
               finish()
           }
            //点击全屏
           it.cvVideoView.fullscreenButton.setOnClickListener { view->
               it.cvVideoView.startWindowFullscreen(this,true,true)
           }
        }

    }

    private fun getFooterView(): View {
        return LayoutInflater.from(this).inflate(R.layout.player_item_footer_white_view,binding?.rv,false)

    }

    private fun getHeaderView(): View {
        val headerViewBinding = DataBindingUtil.inflate<PlayerItemVideoHeaderViewBinding>(
            LayoutInflater.from(this),
            R.layout.player_item_video_header_view,
            binding?.rv,
            false
        )
        headerViewBinding.viewModel = video
        headerViewBinding.executePendingBindings()
        return headerViewBinding.root

    }

    override fun initData() {
        //????? 2个接口数据合并到1个列表中，由于无法保证先后顺序，解决方案笨方法 playerAdapter.addData(0,it.itemList)
        //协程优雅实现
        viewModel.relate(14796).observe(this){
            LoggerUtils.d(TAG,"推荐 ${it.toString()}")
            playerAdapter.addData(0,it.itemList)
        }

        viewModel.comment(14796).observe(this){
            LoggerUtils.d(TAG,"品论 ${it.toString()}")
            playerAdapter.addData(it.itemList)
        }

    }

    override fun initListener() {

    }

    override fun bindLayout(): Int {
        return R.layout.player_activity_player
    }

    override fun getJVMClass(): Class<PlayerViewModel> {
       return PlayerViewModel::class.java
    }

    companion object{
        const val TAG = "PlayerActivity"
    }

//    //点击返回键，如果全屏退出全屏而不是关闭页面
//    override fun onBackPressed() {
//        super.onBackPressed()
//        if (orientationUtils != null) {
//            orientationUtils.backToProtVideo()
//        }
//        if (GSYVideoManager.backFromWindowFull(this)) {
//            return
//        }
//        super.onBackPressed()
//    }

    //暂停
    override fun onPause() {
        GSYVideoManager.onPause()
        super.onPause()
        isPause = true
    }
    //恢复
    override fun onResume() {
        GSYVideoManager.onResume()
        super.onResume()
        isPause = false
    }
    //销毁：释放资源，防止内存泄漏
    //不全
    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
    }
    //屏幕旋转
    @Override
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        if(isPlay && !isPause){
            binding?.cvVideoView?.onConfigurationChanged(this,newConfig
            ,orientationUtils,true,true)
        }
    }

}